﻿#include "tcpServer.h"
#include "mainwindow.h"
extern intListener doorStatus;
extern QStringList STRType;
extern QStringList STRName;
extern QStringList STRsys;

TcpServer* TcpServer::Instance=0;

TcpServer* TcpServer::getInstance()
{
    if(Instance==0)
        Instance =new TcpServer();
    return Instance;
}

TcpServer::TcpServer(QObject *parent): QTcpServer(parent)
{
    tcpClient = TcpClient::getInstance();

}

//
TcpServer::~TcpServer()
{
}

void TcpServer::incomingConnection(qintptr socketDescriptor)
{
    MainWindow::oldExperimentStatus=MainWindow::experimentStatus.get();
    // 当有新连接时，创建一个QTcpSocket
    socket = new QTcpSocket(this);
    socket->setSocketDescriptor(socketDescriptor);
    MainWindow::tcpServerStatus.set(1);

    connect(socket, &QTcpSocket::readyRead, this, [=]() {
        logClient =loghelper::getInstance();

        QByteArray arr = socket->readAll();
        QString str;
        for(int c :arr)
        {
            if(c>=0)
            {
                str += QString(" %1").arg(c, 2, 16, QChar('0')).toUpper();
            }
            else
            {
                str += QString(" %1").arg(c+256, 2, 16, QChar('0')).toUpper();
            }
        }
        str= str.simplified();
        QStringList list=str.split(" ");
        logClient->WriteLog("ServerLog","接收:\n"+str);
        if(list.length()>7){
            if(list[6]=="01")//请求连接
            {
                QString data="62 00 00 3A 00 06 01 01";
                QString checkedData= common->GetCrcCheck(data.toLatin1());
                QString serverData=QString("62 00 00 3A 00 06 01 01 %1 AA 55").arg(checkedData);
                logClient->WriteLog("ServerLog","发送:\n"+serverData);

                QByteArray finalServerInfo=common->GetSendData(serverData);
                sendData(finalServerInfo);
                closeConnect();
            }
            else if(list[6]=="02")//打开仓门
            {
                if(MainWindow::experimentStatus.get()!=1){
                    doorStatus.set(1);
                }else{
                    QString data="62 00 00 3A 00 06 02 02";
                    QString checkedData= common->GetCrcCheck(data.toLatin1());

                    QString serverData=QString("62 00 00 3A 00 06 02 02 %1 AA 55").arg(checkedData);
                    logClient->WriteLog("ServerLog","发送:\n"+serverData);

                    QByteArray finalServerInfo=common->GetSendData(serverData);
                    sendData(finalServerInfo);
                }
                closeConnect();

            }
            else if(list[6]=="03")//关闭仓门
            {
                if(MainWindow::experimentStatus.get()!=1){
                    doorStatus.set(0);
                }else{
                    QString data="62 00 00 3A 00 06 03 02";
                    QString checkedData= common->GetCrcCheck(data.toLatin1());

                    QString serverData=QString("62 00 00 3A 00 06 03 02 %1 AA 55").arg(checkedData);
                    logClient->WriteLog("ServerLog","发送:\n"+serverData);

                    QByteArray finalServerInfo=common->GetSendData(serverData);
                    sendData(finalServerInfo);
                }
                closeConnect();
            }
            else if(list[6]=="04")//启动实验
            {
                if(MainWindow::experimentStatus.get()==0 ){
                    QSqlDatabase db = dbHelper::openConnection();
                    QSqlQuery query(db);

                    db.transaction();

                    MainWindow::experimentGuid = common->GetGuid();
                    QString sql=QString("Delete from ExperimentInfo");
                    query.exec(sql);
                    query.clear();

                    QDateTime dateTime = QDateTime::currentDateTime();

                    QString expId= common->SixteenToTen(list[8]);
                    QString consumableType=common->SixteenToTen(list[9]);

                    QString experimentName=QString::number(dateTime.date().year())+GetDateString(dateTime.date().month())+GetDateString(dateTime.date().day())+GetDateString(dateTime.time().hour())+GetDateString(dateTime.time().minute())+GetDateString(dateTime.time().second());
                    sql=QString("Insert into ExperimentInfo values ("
                                "'%1','%2','%3','','','','未启动','',(Select Name from ItemCode Where code='%4' and DicCode='6'),'')").arg(MainWindow::experimentGuid,experimentName,expId,consumableType);
                    query.exec(sql);

                    sql="Delete from SampleInfo";
                    query.exec(sql);

                    sql="Delete from SampleAccessInfo";
                    query.exec(sql);

                    for(int i=10;i<list.length()-4;i+=5){
                        QString colNum="0";
                        QString rowNum="0";

                        QString pos= common->SixteenToTen(list[i]);
                        QString type=common->SixteenToTen(list[i+1]);
                        QString conc=common->SixteenToTen(list[i+2]+" "+list[i+3]);

                        if(pos.toInt()%8==0){
                            rowNum="7";
                            colNum=QString::number(pos.toInt()/8-1);
                        }else {
                            rowNum=QString::number(pos.toInt()%8-1);
                            colNum=QString::number(pos.toInt()/8);
                        }

                        QString sampleGuid=common->GetGuid();
                        sql=QString("Insert into SampleInfo values('%1','%2','%3','%4','%5',(Select Name from ItemCode where Code='%6' and DicCode='2'),'%7','%8')").arg( sampleGuid,MainWindow::experimentGuid,colNum,rowNum,pos,type,QString::number(conc.toDouble()/1000),pos);
                        query.exec(sql);

                        QString access= common->SixteenToTwo(list[i+4]);
                        if(access[0]=="1"){
                            sql=QString("Insert into SampleAccessInfo values('%1','%2','%3','')").arg( common->GetGuid(),sampleGuid,"FAM");
                            query.exec(sql);
                        }
                        if(access[1]=="1"){
                            sql=QString("Insert into SampleAccessInfo values('%1','%2','%3','')").arg( common->GetGuid(),sampleGuid,"VIC");
                            query.exec(sql);
                        }
                        if(access[2]=="1"){
                            sql=QString("Insert into SampleAccessInfo values('%1','%2','%3','')").arg( common->GetGuid(),sampleGuid,"ROX");
                            query.exec(sql);
                        }
                        if(access[3]=="1"){
                            sql=QString("Insert into SampleAccessInfo values('%1','%2','%3','')").arg( common->GetGuid(),sampleGuid,"CY5");
                            query.exec(sql);
                        }
                    }

                    db.commit();

                    MainWindow::startExperiment.set(1);
                }
                else if(MainWindow::experimentStatus.get()==1)
                {
                    QString data="62 00 00 3A 00 06 04 02";
                    QString checkedData= common->GetCrcCheck(data.toLatin1());
                    QString serverData=QString("62 00 00 3A 00 06 04 02 %1 AA 55").arg(checkedData);
                    logClient->WriteLog("ServerLog","发送:\n"+serverData);

                    QByteArray finalServerInfo=common->GetSendData(serverData);
                    sendData(finalServerInfo);
                    closeConnect();

                }

            }
            else if(list[6]=="05")//停止实验
            {
                MainWindow::startExperiment.set(2);
            }
            else if(list[6]=="06")//设备状态
            {
                if(MainWindow::experimentStatus.get()==1){
                    QString data="62 00 00 3A 00 06 06 01";
                    QString checkedData= common->GetCrcCheck(data.toLatin1());
                    QString serverData=QString("62 00 00 3A 00 06 06 01 %1 AA 55").arg(checkedData);
                    logClient->WriteLog("ServerLog","发送:\n"+serverData);

                    QByteArray finalServerInfo=common->GetSendData(serverData);
                    sendData(finalServerInfo);
                    closeConnect();
                }
                else if(MainWindow::experimentStatus.get()==2){
                    QString data="62 00 00 3A 00 06 06 03";
                    QString checkedData= common->GetCrcCheck(data.toLatin1());

                    QString serverData=QString("62 00 00 3A 00 06 06 03 %1 AA 55").arg(checkedData);
                    logClient->WriteLog("ServerLog","发送:\n"+serverData);

                    QByteArray finalServerInfo=common->GetSendData(serverData);
                    sendData(finalServerInfo);
                    closeConnect();
                }
                else if(MainWindow::experimentStatus.get()==3){
                    QString data="62 00 00 3A 00 06 06 02";
                    QString checkedData= common->GetCrcCheck(data.toLatin1());

                    QString serverData=QString("62 00 00 3A 00 06 06 02 %1 AA 55").arg(checkedData);
                    logClient->WriteLog("ServerLog","发送:\n"+serverData);

                    QByteArray finalServerInfo=common->GetSendData(serverData);
                    sendData(finalServerInfo);
                    closeConnect();
                }
                else if(MainWindow::experimentStatus.get()==0){
                    QString data="62 00 00 3A 00 06 06 04";
                    QString checkedData= common->GetCrcCheck(data.toLatin1());

                    QString serverData=QString("62 00 00 3A 00 06 06 04 %1 AA 55").arg(checkedData);
                    logClient->WriteLog("ServerLog","发送:\n"+serverData);

                    QByteArray finalServerInfo=common->GetSendData(serverData);
                    sendData(finalServerInfo);
                    closeConnect();
                }
            }
            else if(list[6]=="07")//模型配置
            {
                QString GeneticAnalysers;
                QString ReagentKitType;
                QString ReagentKitName;
                QSqlDatabase db = dbHelper::openConnection();
                QSqlQuery query(db);

                QString sql="Select Name From ItemCode Where DicCode='14'";
                query.exec(sql);
                int num=0;
                while (query.next()) {
                    if(num==list[7].toInt()-1){
                        GeneticAnalysers=query.value("Name").toString();
                    }
                    num++;
                }
                STRType.clear();
                STRName.clear();
                STRsys.clear();
                QString result="";
                for(int i=8;i<list.length()-4;i+=3)
                {
                    sql="Select Name,Code From ItemCode Where DicCode='15'";
                    query.exec(sql);
                    QString code;
                    num=0;
                    while (query.next()) {
                        if(num==list[i].toInt()-1){
                            ReagentKitType=query.value("Name").toString();
                            STRType.append(ReagentKitType);
                            code=query.value("Code").toString();
                        }
                        num++;
                    }

                    sql=QString("Select Name From ItemCode Where DicCode='%1'").arg(code);
                    query.exec(sql);
                    num=0;
                    while (query.next()) {
                        if(num==list[i+1].toInt()-1){
                            ReagentKitName=query.value("Name").toString();
                            STRName.append(ReagentKitName);
                        }
                        num++;
                    }

                    QString System=common->SixteenToTen(list[i+2]);
                    STRsys.append(System);
                    sql=QString("Select count(*) Num From DataAnalyseConfig Where GeneticAnalysers='%1' and ReagentKitType='%2' and ReagentKitName='%3' and System='%4'").arg(GeneticAnalysers,ReagentKitType,ReagentKitName,System);
                    query.exec(sql);
                    QString exist;
                    while (query.next()) {
                        exist=query.value("Num").toInt()>0?"00":"01";
                    }
                    result.append(QString (" %1").arg(exist));
                }

                QString data=QString("62 00 00 3A 00 0A 07 %1").arg(result);
                QString checkedData= common->GetCrcCheck(data.toLatin1());
                QString serverData=QString("%1 %2 AA 55").arg(data,checkedData);
                logClient->WriteLog("ServerLog","发送:\n"+serverData);

                QByteArray finalServerInfo=common->GetSendData(serverData);
                sendData(finalServerInfo);
                closeConnect();
            }
        }

    });
}

void TcpServer::closeConnect(){
    socket->disconnect();
}

void TcpServer::sendData(QByteArray array){
    socket->write(array);
}

QString TcpServer::GetDateString(int val){
    return QString::number(val).length()==2?QString::number(val): "0"+QString::number(val);
}
